package com.milk.controller.user;


import com.milk.entity.Milktea;
import com.milk.entity.UserCollect;
import com.milk.result.Result;
import com.milk.service.IMilkteaService;
import com.milk.service.UserCollectService;
import com.milk.vo.MilkteaVO;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController("userMilkTea")
@RequestMapping("/user/milkTea")
@Slf4j
public class MilkTeaController {
    @Autowired
    private IMilkteaService milkteaService;
    @Autowired
    private UserCollectService userCollectService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 根据分类id查询奶茶
     * @param id
     * @return
     */
    @GetMapping("/list/{id}")
    @ApiModelProperty("根据分类id查询奶茶")
    public Result<List<MilkteaVO>> listByCategoryId(@PathVariable Long id){
        log.info("分类id {}",id);
        String key ="milkteaCategory_"+id;

        //查询缓存信息
        List<MilkteaVO> list = (List<MilkteaVO>) redisTemplate.opsForValue().get(key);
        //判断缓存中是否有categoryId数据
        if (list != null){
            return Result.success(list);
        }
        list = milkteaService.listCategoryId(id);

        //查询后把查询的数据上传到redis中
        redisTemplate.opsForValue().set(key,list);
        return Result.success(list);
    }

    /**
     * 根据id查询奶茶
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiModelProperty("根据id查询奶茶")
    public Result<MilkteaVO> selectById(@PathVariable Long id){
        String key = "milktea_"+id;
        //查询缓存中数据
        MilkteaVO milkteaVO = (MilkteaVO) redisTemplate.opsForValue().get(key);
        //判断缓存中是否有数据
        if (milkteaVO != null){
            return Result.success(milkteaVO);
        }
        milkteaVO = milkteaService.selectById(id);

        //把获得的数据存到缓存中
        redisTemplate.opsForValue().set(key,milkteaVO);

        return Result.success(milkteaVO);
    }

    /**
     * 首页展示奶茶新品
     * @return
     */
    @GetMapping("/new")
    public Result<List<Milktea>> selectNew(){
        List<Milktea> list = milkteaService.selectNew();
        return Result.success(list);
    }

    /**
     * 判断用户是否收藏此口味
     * @param userCollect
     * @return
     */
    @PostMapping("/isCollect")
    public Boolean isCollect(@RequestBody UserCollect userCollect){
        log.info("口味信息 = {}",userCollect);
        return userCollectService.isCollect(userCollect);
    }
}
